package club.jdiy.admin.service.impl;

import club.jdiy.core.base.JDiyBaseService;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.admin.dao.RoleDao;
import club.jdiy.admin.entity.Role;
import club.jdiy.admin.entity.User;
import club.jdiy.admin.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class RoleServiceImpl extends JDiyBaseService<Role, RoleDao, Integer>
        implements RoleService {


    @Override
    @Transactional
    public void delete(Role role) {
        Role vo = dao.findById(role.getId()).orElseThrow(() -> new JDiyException("删除失败，角色不存在或刚被其它人删除！"));
        if (vo.isSys()) throw new JDiyException("系统内置角色无法删除.");
        if (vo.getUserList().size() > 0) {
            if (vo.getUserList().stream().anyMatch(u -> !Boolean.TRUE.equals(u.getRemoved()))) {
                throw new JDiyException("对不起，此角色下面还有用户，因此不能删除！");
            } else {
                vo.setRemoved(true);
                dao.save(vo);
            }
        } else {
            dao.delete(vo);
        }


    }

    @Transactional
    @Override
    public Role logicSave(Role vo) {
        Role p = dao.findById(vo.getId()).orElseGet(() -> {
            vo.setId(null);
            return vo;
        });
        p.setName(vo.getName());
        p.setSortIndex(vo.getSortIndex());
        p.setRemark(vo.getRemark());
        if (vo.getGrantAuth() != null) p.setGrantAuth(vo.getGrantAuth());
        p = dao.save(p);
        return p;
    }
}
